package com.itheima.article.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.itheima.article.pojo.ApArticleConfig;
import com.itheima.article.service.ApArticleConfigService;
import com.itheima.common.constants.BusinessConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @version 1.0
 * @description 监听Kafka消息，同步文章上下架状态
 * @package com.itheima.article.listener
 */
@Component
@Slf4j
public class ApArticleConfigListener {

    @Autowired
    private ApArticleConfigService apArticleConfigService;

    /**
     * 文章与自媒体上下线同步
     * @param msgRecord
     */
    @KafkaListener(topics = BusinessConstants.MqConstants.WM_NEWS_DOWN_OR_UP_TOPIC)
    public void upOrDown(ConsumerRecord<String,String> msgRecord){
        //1. 获取消息信息
        String topic = msgRecord.topic();
        int partition = msgRecord.partition();
        String jsonString = msgRecord.value();
        log.info("文章上下架开始: t={},p={},msg={}", topic, partition, jsonString);
        //2.1 解析消息内容
        JSONObject json = JSON.parseObject(jsonString);
        //2.2 获取文章id
        Long articleId = json.getLong("articleId");
        //2.3 获取上下线的值
        Integer enable = json.getInteger("enable");
        //3.1 构建更新对象
        LambdaUpdateWrapper<ApArticleConfig> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(ApArticleConfig::getIsDown, enable);
        //3.2 设置更新条件
        updateWrapper.eq(ApArticleConfig::getArticleId, articleId);
        //3.3  执行更新并记录日志
        if (apArticleConfigService.update(updateWrapper)) {
            log.info("文章上下架配置成功: t={},p={},msg={}", topic, partition, jsonString);
        }else {
            log.info("文章上下架配置失败: t={},p={},msg={}", topic, partition, jsonString);
        }
    }
}
